<?php

namespace app\api\controller;


use app\common\controller\ApiController;
use think\facade\Db;

class Evaluation extends ApiController
{
    protected $noNeedLogin = [];
    protected $mustLogin = [];

    //更新技术主题
    public function updateTheme($techPoint)
    {
        $first_theme_name = $techPoint['first_theme_name'];
        $second_theme_name = $techPoint['second_theme_name'];
        $tech_point_name = $techPoint['tech_point_name'];
        $tech_development_prediction = $techPoint['tech_development_prediction'];


        $firstThemeData = Db::name('jsyc_technical_theme')->where(['name' => $first_theme_name, 'parent_id' => 0, 'delete_time' => 0])->find();
        if (!$firstThemeData) {
            $firstTheme = Db::name('jsyc_technical_theme')->insertGetId([
                'name' => $first_theme_name,
                'parent_id' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            //添加二级主题
            $secondTheme = Db::name('jsyc_technical_theme')->insertGetId([
                'name' => $second_theme_name,
                'parent_id' => $firstTheme,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            //添加技术点
            $techPointId = Db::name('jsyc_technical_theme')->insertGetId([
                'name' => $tech_point_name,
                'parent_id' => $secondTheme,
                'tech_development_prediction' => $tech_development_prediction,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            //更新技术点
            $theme_ids = $firstTheme . ',' . $secondTheme . ',' . $techPointId;
            Db::name('jsyc_task_tech_point')->where(['id' => $techPoint['id'], 'delete_time' => 0])->update(['theme_ids' => $theme_ids]);
        } else {
            //查找二级主题
            $secondThemeData = Db::name('jsyc_technical_theme')->where(['name' => $second_theme_name, 'parent_id' => $firstThemeData['id'], 'delete_time' => 0])->find();
            $sercondId = $secondThemeData ? $secondThemeData['id'] : 0;
            if (!$secondThemeData) {
                $secondTheme = Db::name('jsyc_technical_theme')->insertGetId([
                    'name' => $second_theme_name,
                    'parent_id' => $firstThemeData['id'],
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
                $sercondId = $secondTheme;
            }
            //判断技术点是否存在
            $techPointData = Db::name('jsyc_technical_theme')->where(['name' => $tech_point_name, 'parent_id' => $sercondId, 'delete_time' => 0])->find();
            $techPointId = $techPointData ? $techPointData['id'] : 0;
            if (!$techPointData) {
                //添加技术点
                $techPointId = Db::name('jsyc_technical_theme')->insertGetId([
                    'name' => $tech_point_name,
                    'parent_id' => $sercondId,
                    'tech_development_prediction' => $tech_development_prediction,
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
            } else {
                //更新技术点
                Db::name('jsyc_technical_theme')->where(['id' => $techPointId, 'delete_time' => 0])->update(['update_time' => time(), 'tech_development_prediction' => $tech_development_prediction]);
            }
            //更新技术点
            $theme_ids = $firstThemeData['id'] . ',' . $sercondId . ',' . $techPointId;
            Db::name('jsyc_task_tech_point')->where(['id' => $techPoint['id'], 'delete_time' => 0])->update(['theme_ids' => $theme_ids]);
        }
    }

    //写一个公共记录日志方法 按日期分目录,自定义日志类型,不同日期不同文件指定一个存放日志目录
    public function zdyLog($msg, $type = 'info', $logDir = 'zdylog')
    {
        //创建日志目录
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);
        }
        $date = date('Y-m-d');
        //日志中记录当前时间
        $time = date('H:i:s');
        $filename = $type . '_' . $date . '.log';
        file_put_contents($logDir . '/' . $filename, $time . ' ' . $msg . PHP_EOL, FILE_APPEND);
    }

    // 数据转树形结构
    protected function buildTree($data, $pk = 'id', $pid = 'parent_id', $children = 'children', $root = 0)
    {
        $tree = [];
        foreach ($data as $item) {
            if ($item[$pid] == $root) {
                $tree[] = $item;
            }
        }
        foreach ($tree as $key => $item) {
            $tree[$key][$children] = $this->buildTree($data, $pk, $pid, $children, $item[$pk]);
        }
        return $tree;
    }

    //同步识别接口
    public function syncIdentify()
    {
        //获取完整的技术主题树
        $themeList = Db::name('jsyc_technical_theme')->where(['delete_time' => 0])->order('create_time', 'desc')->select();
        $themeList = empty($themeList) ? [] : collect($themeList)->toArray();
        //判断是否为新添加的技术主题 
        foreach ($themeList as $key => $item) {
            //如果update_time在当天就加is_new=true 否则false
            $themeList[$key]['is_new'] = date('Y-m-d', $item['update_time']) == date('Y-m-d') ? true : false;
            $themeList[$key]['techDevelopmentPrediction'] = $item['tech_development_prediction'] ? json_decode($item['tech_development_prediction'], true) : '';
            //只有最后一层加techDevelopmentPrediction 其他层都为空
            unset($themeList[$key]['create_time']);
            unset($themeList[$key]['update_time']);
            unset($themeList[$key]['delete_time']);
            unset($themeList[$key]['tech_development_prediction']);
        }
        $themeList = $this->buildTree($themeList, 'id', 'parent_id');
        return $themeList;
        // // 使用 PHP cURL 调用外部接口获取分析结果
        // $url =  env('identify.apiurl') . 'common/keytech/add';
        // $apipwd = env('identify.apipwd');
        // $requestParam = [
        //     'techContent' => $themeList,
        // ];
        // $payload = json_encode($requestParam);
        // $this->zdyLog($payload, 'info');
        // // 创建curl资源
        // $ch = curl_init();
        // // 设置curl选项
        // curl_setopt_array($ch, [
        //     CURLOPT_URL => $url,
        //     CURLOPT_RETURNTRANSFER => true,
        //     CURLOPT_TIMEOUT => 5 * 60, // 5 分钟超时
        //     CURLOPT_HTTPHEADER => [
        //         'Content-Type: application/json',
        //         'apipwd:' . $apipwd,
        //         'User-Agent: PostmanRuntime/7.29.2', // 关键：完全相同的 User-Agent
        //         'Accept: */*',                // 关键：Postman 用 */* 而不是 application/json
        //         'Cache-Control: no-cache',
        //         'Accept-Encoding: gzip, deflate, br',
        //         'Connection: keep-alive',
        //         'Expect:',                    // 关键：禁用 Expect 头
        //     ],
        //     CURLOPT_POST => true,
        //     CURLOPT_POSTFIELDS => $payload,
        //     CURLOPT_SSL_VERIFYHOST => 0,
        //     CURLOPT_SSL_VERIFYPEER => false,
        //     // 移除VERBOSE=true或将输出重定向到文件，避免影响返回结果
        //     CURLOPT_VERBOSE => false,
        //     // 添加更多调试选项
        //     CURLOPT_HEADER => false,
        //     CURLOPT_FOLLOWLOCATION => true,
        //     CURLOPT_MAXREDIRS => 5,
        // ]);

        // // 执行curl请求
        // $body = curl_exec($ch);
        // $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // $err = curl_error($ch);
        // $errno = curl_errno($ch);

        // // 记录请求信息
        // $this->zdyLog('请求URL: ' . $url, 'info');
        // $this->zdyLog('HTTP状态码: ' . $httpCode, 'info');
        // $this->zdyLog('curl错误号: ' . $errno, 'info');
        // $this->zdyLog('curl错误信息: ' . $err, 'info');
        // $this->zdyLog('响应体长度: ' . (empty($body) ? 0 : strlen($body)), 'info');
        // $this->zdyLog('响应体内容: ' . (empty($body) ? '空' : substr($body, 0, 500) . '...'), 'info');

        // // 关闭curl资源
        // curl_close($ch);

        // // 首先检查curl_exec是否返回false（表示请求失败）
        // if ($body === false) {
        //     $this->zdyLog('curl请求执行失败: ' . $err, 'error');
        //     return false;
        // }

        // // 检查响应体是否为空
        // if (empty($body)) {
        //     $this->zdyLog('响应体为空，HTTP状态码: ' . $httpCode, 'warning');
        //     // 即使响应体为空，如果HTTP状态码是200，也可以继续处理
        //     // 但需要处理空响应的情况
        //     $result = [];
        // } else {
        //     // 解析JSON响应
        //     $result = json_decode($body, true);
        //     if (json_last_error() !== JSON_ERROR_NONE) {
        //         $this->zdyLog('JSON解析失败: ' . json_last_error_msg() . ', 响应体: ' . $body, 'error');
        //         return false;
        //     }
        // }
        // if (!isset($result['code']) || $result['code'] != 200) {
        //     $this->zdyLog(json_encode($result), 'error');
        //     // $this->error('响应解析失败：' . json_last_error_msg());
        //     return false;
        // } else {
        //     $this->zdyLog(json_encode($result), 'success');
        // }
 
        // return true;
    }

    //更新评估结果
    public function updateTask()
    {
        $params = $this->request->param();
        $themeList = [];
        //检查技术点是否存在
        $techPoint = Db::name('jsyc_task_tech_point')->where(['id' => $params['tech_point_id'], 'delete_time' => 0])->find();
        if (!$techPoint) {
            $this->error('技术点不存在');
        }
        //检查任务是否存在
        $taskDetail = Db::name('jsyc_task')->where(['id' => $techPoint['task_id'], 'delete_time' => 0])->find();
        if (!$taskDetail) {
            $this->error('任务不存在');
        }
        //更新评估结果
        $result = Db::name('jsyc_task_tech_point')->where(['id' => $params['tech_point_id'], 'delete_time' => 0])->update(['result' => $params['result']]);
        if (!$result) {
            $this->error('操作失败');
        }
        if ($params['result'] == 1) {
            //更新技术主题
            $this->updateTheme($techPoint);
            $themeList = $this->syncIdentify(); //同步技术点标识
        }
        $this->success('操作成功', ['themeList' => $themeList]);
    }

    //验证评估码
    public function verifyEvaluationCode()
    {
        $params = $this->request->param();
        //查找技术点
        $techPoint = Db::name('jsyc_task_tech_point')->where(['id' => $params['tech_point_id'], 'delete_time' => 0])->find();
        if (!$techPoint) {
            $this->error('技术点不存在');
        }

        //检查评估码是否存在
        $evaluationCode = Db::name('jsyc_task')->where(['id' => $techPoint['task_id'], 'evaluation_code' => $params['evaluation_code'], 'delete_time' => 0])->find();
        if (!$evaluationCode) {
            $this->error('评估码不存在');
        }
        //返回技术点详情
        $techPointDetail = Db::name('jsyc_task_tech_point')->where(['id' => $params['tech_point_id'], 'delete_time' => 0])->find();

        $this->success('评估码验证成功', ['techPointDetail' => $techPointDetail]);
    }

    //评估详情
    public function getEvaluationDetail()
    {
        $params = $this->request->param();
        //根据技术点id 查找评估列表
        $evaluationList = Db::name('jsyc_evaluation')->where(['tech_point_id' => $params['tech_point_id'], 'delete_time' => 0])->select();
        if (!$evaluationList) {
            $this->success('获取成功', []);
        }
        $evaluationList = !empty($evaluationList) ? $evaluationList->toArray() : [];
        foreach ($evaluationList as $key => $value) {
            $evaluationList[$key]['expert_name'] = Db::table('tk_sys_user')->where(['user_id' => $value['expert_uid']])->value('user_name');
            $evaluationList[$key]['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
        }

        //查找技术点
        $techPoint = Db::name('jsyc_task_tech_point')->where(['id' => $params['tech_point_id'], 'delete_time' => 0])->find();

        $this->success('获取成功', ['evaluationList' => $evaluationList, 'techPoint' => $techPoint]);
    }

    //添加评估
    public function addEvaluation()
    {
        $params = $this->request->param();
        $techPointId = $params['techpointid'];
        unset($params['techpointid']);
        //检查技术点是否存在
        $techPoint = Db::name('jsyc_task_tech_point')->where(['id' => $techPointId, 'delete_time' => 0])->find();
        if (!$techPoint) {
            $this->error('技术点不存在');
        }
        //检查任务是否存在
        $taskDetail = Db::name('jsyc_task')->where(['id' => $techPoint['task_id'], 'delete_time' => 0])->find();
        if (!$taskDetail) {
            $this->error('任务不存在');
        }
        //查找该任务已评估数量
        $evaluationCount = Db::name('jsyc_evaluation')->where(['tech_point_id' => $techPointId, 'task_id' => $techPoint['task_id'], 'delete_time' => 0])->count();
        //判断专家数量 
        if ($techPoint['experts_num'] <= $evaluationCount) {
            //更新评估状态
            Db::name('jsyc_task_tech_point')->where(['id' => $techPointId, 'delete_time' => 0])->update(['state' => 3, 'update_time' => time()]);
            // Db::name('jsyc_task')->where(['id' => $params['task_id'], 'delete_time' => 0])->update(['assess_state' => 3, 'update_time' => time()]);
            $this->error('该任务已被评估');
        }

        //一个专家只能评估一个任务
        $expertEvaluation = Db::name('jsyc_evaluation')->where(['tech_point_id' => $techPointId, 'task_id' => $techPoint['task_id'], 'expert_uid' => $this->uid, 'delete_time' => 0])->find();
        if ($expertEvaluation) {
            $this->error('同一个任务一个专家只能评估一次，您已经评估过该任务');
        }
        //添加事务
        Db::name('jsyc_evaluation')->startTrans();
        try {
            $params['create_time'] = time();
            $params['expert_uid'] = $this->uid;
            $params['tech_point_id'] = $techPointId;
            $params['task_id'] = $techPoint['task_id'];
            $result = Db::name('jsyc_evaluation')->insert($params);
            if (!$result) {
                throw new \Exception('评估失败');
            }
            //查找该技术点任务已评估数量
            $evaluationCount = Db::name('jsyc_evaluation')->where(['tech_point_id' => $techPointId, 'task_id' => $techPoint['task_id'], 'delete_time' => 0])->count();
            //判断专家数量 
            if ($techPoint['experts_num'] <= $evaluationCount) {
                //更新评估状态
                Db::name('jsyc_task_tech_point')->where(['id' => $techPointId, 'delete_time' => 0])->update(['state' => 3, 'update_time' => time()]);
            } else {
                //更新评估状态
                Db::name('jsyc_task_tech_point')->where(['id' => $techPointId, 'delete_time' => 0])->update(['state' => 2, 'update_time' => time()]);
            }

            // 判断任务的评估状态
            $taskAssessStateCount = Db::name('jsyc_evaluation')->where(['task_id' => $techPoint['task_id'], 'delete_time' => 0])->count();
            //查该任务下应该总共有几个专家
            $expertsNum = Db::name('jsyc_task_tech_point')->where(['task_id' => $techPoint['task_id'], 'delete_time' => 0])->sum('experts_num');
            //判断是否所有专家都评估了
            if ($taskAssessStateCount == $expertsNum) {
                //更新任务状态为已评估
                Db::name('jsyc_task')->where(['id' => $techPoint['task_id'], 'delete_time' => 0])->update(['assess_state' => 3, 'update_time' => time()]);
            } else {
                //更新任务状态为评估中
                Db::name('jsyc_task')->where(['id' => $techPoint['task_id'], 'delete_time' => 0])->update(['assess_state' => 2, 'update_time' => time()]);
            }
            //提交事务
            Db::name('jsyc_evaluation')->commit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit;
            //回滚事务
            Db::name('jsyc_evaluation')->rollback();
            $this->error('评估失败');
        }
        $this->success('评估成功');
    }

    //待评估列表
    public function getEvaluationList()
    {
        // $list = Db::name('jsyc_task')->where(['state' => 2, 'assess_state' => 1])->order('create_time desc')->select();
        $list = Db::name('jsyc_task_tech_point')->where(['state' => 1])->where('experts_num', '>', 0)->order('create_time desc')->select();
        $list = !empty($list) ? $list->toArray() : [];
        foreach ($list as $key => $value) {
            $list[$key]['task'] = Db::name('jsyc_task')->where(['id' => $value['task_id'], 'delete_time' => 0])->find();
        }
        $this->success('获取成功', $list);
    }

    //评估进行中列表
    public function getOngoingAssessmentList()
    {
        $userInfo = Db::table('tk_sys_user')->where(['user_id' => $this->uid, 'delete_time' => NULL])->find();
        if ($userInfo['user_type'] == 1) { //超管查所有
            $list = Db::name('jsyc_task_tech_point')->where(['state' => 2])->where('experts_num', '>', 0)->order('create_time desc')->select();
            $list = !empty($list) ? $list->toArray() : [];
            foreach ($list as $key => $value) {
                $list[$key]['task'] = Db::name('jsyc_task')->where(['id' => $value['task_id'], 'delete_time' => 0])->find();
            }
            $this->success('获取成功', $list);
        } else {

            $list = Db::name('jsyc_task_tech_point')
                ->alias('tp')
                ->join('jsyc_evaluation t', 'tp.id = t.tech_point_id')
                ->where(['tp.state' => 2])
                ->where('tp.experts_num', '>', 0)
                ->where('t.expert_uid', '<>', $this->uid)
                ->field('tp.*')
                ->group('tp.id')
                ->order('tp.create_time desc')
                ->select();

            $list = !empty($list) ? $list->toArray() : [];
            foreach ($list as $key => $value) {
                $list[$key]['task'] = Db::name('jsyc_task')->where(['id' => $value['task_id'], 'delete_time' => 0])->find();
            }
            $this->success('获取成功', $list);

            // //联查
            // $list = Db::name('jsyc_task')
            //     ->alias('t')
            //     ->where('t.assess_state', 2)
            //     ->where('t.state', 2)
            //     ->join('jsyc_evaluation e', 't.id = e.task_id')
            //     ->where('e.expert_uid', '<>', $this->uid)
            //     ->field('t.*')
            //     ->order('t.create_time desc')
            //     ->group('t.id') // 添加分组以避免一对多查询出现多条重复数据
            //     ->select();
        }

        // $this->success('获取成功', $list);
    }


    //已评估列表
    public function getAssessEvaluationList()
    {
        $list = Db::name('jsyc_task_tech_point')->where(['state' => 3])->where('experts_num', '>', 0)->order('create_time desc')->select();
        $list = !empty($list) ? $list->toArray() : [];
        foreach ($list as $key => $value) {
            $list[$key]['task'] = Db::name('jsyc_task')->where(['id' => $value['task_id'], 'delete_time' => 0])->find();
            //取最后一条评估专家信息
            $evaluation = Db::name('jsyc_evaluation')->where(['tech_point_id' => $value['id'], 'task_id' => $value['task_id'], 'delete_time' => 0])->order('create_time desc')->find();
            if ($evaluation) {
                $list[$key]['create_time'] = date('Y-m-d H:i:s', $evaluation['create_time']);
                $expert_uid = $evaluation['expert_uid'];
                $list[$key]['expert_name'] = Db::table('tk_sys_user')->where(['user_id' => $expert_uid, 'delete_time' => NULL])->value('user_name');
            } else {
                $list[$key]['create_time'] = '';
            }
        }
        $this->success('获取成功', $list);
        // $list = Db::name('jsyc_task')->where(['state' => 2, 'assess_state' => 3])->order('create_time desc')->select();
        // $list = !empty($list) ? $list->toArray() : [];
        // foreach ($list as $key => $value) {
        //     //取最后一条评估专家信息
        //     $evaluation = Db::name('jsyc_evaluation')->where(['task_id' => $value['id'], 'delete_time' => 0])->order('create_time desc')->find();
        //     if ($evaluation) {
        //         $list[$key]['create_time'] = date('Y-m-d H:i:s', $evaluation['create_time']);
        //         $expert_uid = $evaluation['expert_uid'];
        //         $list[$key]['expert_name'] = Db::table('tk_sys_user')->where(['user_id' => $expert_uid, 'delete_time' => NULL])->value('user_name');
        //     } else {
        //         $list[$key]['create_time'] = '';
        //     }
        // }
        // $this->success('获取成功', $list);
    }

    //评估统计
    public function getEvaluationStatistics()
    {
        //总待评估数量
        // $totalOngoing = Db::name('jsyc_task')->where(['state' => 2, 'assess_state' => 1])->count();
        $totalOngoing = Db::name('jsyc_task_tech_point')->where(['state' => 1])->where('experts_num', '>', 0)->count();
        //总进行中的数量
        $totalOngoingAssessment = Db::name('jsyc_task_tech_point')->where(['state' => 2])->where('experts_num', '>', 0)->count();

        //总已评估数量
        $totalAssess = Db::name('jsyc_task_tech_point')->where(['state' => 3])->where('experts_num', '>', 0)->count();
        // $totalAssess = Db::name('jsyc_task')->where(['state' => 2, 'assess_state' => 3])->count();
        $this->success('获取成功', ['totalOngoing' => $totalOngoing, 'totalOngoingAssessment' => $totalOngoingAssessment, 'totalAssess' => $totalAssess]);
    }
}
